<template>
  <div>
    <search-form
      :search-config="searchConfig"
      :label-width="150"
      @clear="clearSearch"
      @search="handleSearch"
    />
    <table-box
      ref="refTable"
      table-size="mini"
      :table-config="tableConfig"
      show-selection
      dragable
      no-request
      :selected-arry.sync="tableSelected"
      :other-filters="otherFilters"
      @btnOperate="btnOperate"
      @selection-change="selectionChangeHandle"
    >
      <template slot="setting-before">
        <el-popover
          style="width:30%"
          placement="bottom"
          title="导入示例"
          trigger="hover"
        >
          <div>
            <el-image fit="contain" :src="PIC" />
          </div>
          <el-button slot="reference" type="text" size="mini">导入模板示例</el-button>
        </el-popover>
        手工新增数据默认门店：
        <el-select
          style="width:300px"
          placeholder="请选择"
          :value="shopData"
          value-key="shopCode"
          @change="changeShop"
        >
          <el-option
            v-for="item in shopList"
            :key="item.shopCode"
            :label="item.shopName"
            :value="item"
          />
        </el-select>
      </template>
    </table-box>
    <export-files
      v-if="exportVisible"
      title="导出"
      :visible.sync="exportVisible"
      :config="exportConfig"
    />
    <import-files
      v-if="importVisible"
      title="导入"
      :visible.sync="importVisible"
      :config="importConfig"
      @success="handleSuccess"
    />
    <!--
      在产状态：在产
and采购控制状态：常规采购
and是否异形：否
and（是否成品渠道：是  or  是否定制渠道：是）
isFinishedProduct  isCustomized
     -->
    <filed-select
      v-if="selectVisible"
      ref="refSelect"
      v-model="filedTable"
      :visible.sync="selectVisible"
      :props="{label:'name',value:'code'}"
      multiple
      :config="{
        title:'产品表',
        rowKey:'productCode',
        interfacePath:`/select-service/api/v1/productInfo/page`,
        method:'post',
        filtersRaw:[
          { 'id': 'customizeType', 'property': 'customizeType', 'operator': '=', 'value': 'NORM' }
        ],
        paramsRaw:{},
        defaultData:shopData,
        setting:[ {prop:'productCode',title:'产品编码',width:'100'},
                  {prop:'productName',title:'产品描述'},
                  {prop:'prodModelName',width:'70',title:'型号'},
                  {prop:'productCategoryName',width:'70',title:'品类'},
                  {prop:'saleSeriesName',width:'70',title:'系列'}]
      }"
      @success="refreshTable"
    />
    <edit v-if="showEdit" :shop-list="shopList" :visible.sync="showEdit" :table-data="tableSelected" @success="refreshTable" />
  </div>
</template>
<script>
import PIC from '@/assets/exportSample.png'
import edit from './Edit.vue'
import filedSelect from './FiledSelect.vue'
import { deleteBatch, getShopList } from '@/api/display/salesData'
import { parseTime } from '@/utils'
export default {
  name: 'SalesData',
  components: { filedSelect, edit },
  data() {
    return {
      PIC,
      shopList: [],
      tableSelected: [],
      otherFilters: [],
      filedTable: [],
      shopData: { shopCode: '', shopName: '' },
      selectVisible: false,
      exportVisible: false,
      importVisible: false,
      showEdit: false,
      searchConfig: [
        { label: '产品编码', prop: 'productCode', type: 'text', value: '', placeholder: '' },
        // { label: '门店编码', prop: 'shopCode', type: 'text', value: '', placeholder: '' },
        { label: '型号', prop: 'model', type: 'text', value: '', placeholder: '' }
      ],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/displayHistoryData/page`,
        buttonGroupCode: 'default',
        hideSearchBar: true,
        tabIndex: 0,
        pageSize: 10,
        order: 'desc',
        sort: 'saleTime',
        // 表格字段动态配置
        setting: [
          {
            prop: 'productDescription',
            label: '产品描述',
            minWidth: '140'
          },
          {
            prop: 'model',
            label: '型号',
            minWidth: '120'
          },
          {
            prop: 'productCode',
            label: '产品编码',
            minWidth: '140'
          },
          {
            prop: 'num',
            label: '数量',
            minWidth: '90'
          },
          {
            prop: 'saleTime',
            label: '销售时间',
            minWidth: '130',
            formatData: function(val) { return parseTime(val.saleTime, '{y}-{m}') }
          },
          {
            prop: 'shopCode',
            label: '门店编码',
            minWidth: '140'
          },
          {
            prop: 'shopName',
            label: '门店名称',
            minWidth: '140'
          },
          // {
          //   prop: 'productSize',
          //   label: '尺寸',
          //   minWidth: '140'
          // },
          // {
          //   prop: 'price',
          //   label: '价格',
          //   minWidth: '140'
          // },
          // {
          //   prop: 'productStyle',
          //   label: '款式',
          //   minWidth: '140'
          // },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: '140'
          }
        ],
        btnList: this.isProduction ? null : [{
          buttonName: '新增',
          outerFlag: true,
          optCode: 'add'
        },
        {
          buttonName: '编辑',
          outerFlag: true,
          optCode: 'edit'
        },
        {
          buttonName: '删除',
          outerFlag: true,
          optCode: 'delete'
        },
        {
          buttonName: '导入',
          outerFlag: true,
          optCode: 'import'
        },
        {
          buttonName: '导出',
          outerFlag: true,
          optCode: 'export'
        }]
      }
    }
  },
  computed: {
    exportConfig() {
      return [
        {
          code: 'export',
          name: '历史销售数量',
          dataApi: `${process.env.VUE_APP_BASE_API}/api/v1/displayHistoryData/export/?type=0`, // 同步数据导出api
          filtersRaw: this.otherFilters, // 符合当前查询条件的所有数据行的导出条件(当前数据查询结果对应的条件)
          selectedRows: this.tableSelected, // 当前所选中的数据行
          queryField: 'id'// 指定行导出时使用的查询字段名称
        },
        {
          code: 'exportTemplate',
          name: '历史销售数量模板',
          async: false,
          templateMethod: 'post',
          templateApi: `${process.env.VUE_APP_BASE_API}/api/v1/displayHistoryData/export/?type=1`
        }
      ]
    },
    importConfig() {
      return [{
        code: 'import',
        name: '历史销售数量',
        apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/displayHistoryData/importExcel/?type=1`,
        selectedRows: this.tableSelected,
        paramsRaw: {},
        filtersRaw: this.otherFilters
      }]
    }
  },
  created() {
    getShopList().then(res => {
      if (res.success && res.data.length > 0) {
        this.shopList = res.data
        this.changeShop(this.shopList[0])
        this.otherFilters = [{ 'id': 'shopCode', 'property': 'shopCode', 'operator': '=', 'value': res.data[0].shopCode }]
        this.$nextTick(() => {
          this.refreshTable()
        })
      } else {
        this.$message.warning('当前用户下没有门店')
      }
    })
  },
  methods: {
    changeShop(data) {
      this.shopData = { shopName: data.shopName, shopCode: data.shopCode }
    },
    refreshTable(isOld) {
      if (this.shopList.length === 0) {
        this.$message.warning('当前用户下没有门店')
        return
      }
      this.$refs.refTable.initTableData(isOld ? 'onPage' : '')
    },
    selectionChangeHandle(data) {
      this.tableSelected = data
    },
    // 搜索
    handleSearch(data) {
      if (this.shopList.length === 0) {
        this.$message.warning('当前用户下没有门店')
        return
      }
      this.otherFilters = [...data.filtersRaw, { 'id': 'shopCode', 'property': 'shopCode', 'operator': '=', 'value': this.shopData.shopCode }]
      this.$nextTick(() => {
        this.$refs.refTable.initTableData()
      })
    },
    // 清空搜索
    clearSearch(data) {
    },
    btnOperate(flag) {
      switch (flag) {
        case 'add':
          this.handleAdd()

          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', false)) {
            return
          }
          this.handleEdit()
          break
        case 'delete':
          if (!this.singleJudge(this.tableSelected, '删除', false)) {
            return
          }
          this.handleDelete()
          break
        case 'import':
          this.importVisible = true
          break
        case 'export':
          this.exportVisible = true
          break
        default:
          break
      }
    },
    handleDelete() {
      const data = this.tableSelected.map(v => v.id)
      deleteBatch(data).then(res => {
        if (res.success) this.$message.warning('操作成功')
        this.refreshTable()
      })
    },
    handleAdd() {
      if (this.shopList.length === 0) {
        this.$message.warning('当前用户下没有门店')
        return
      }
      this.selectVisible = true
    },
    handleEdit() {
      this.showEdit = true
      // this.tableSelected
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
